package com.fau.template.service.impl;

import com.fau.template.entity.NmAdmin;
import com.fau.template.entity.NmRole;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.hibernate.Hibernate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.template.service.IUserManagerService;
import com.fau.template.util.Page;

import java.util.Map;
import java.util.Set;

@Service
@Transactional(readOnly = true)
public class UserManagerService extends BaseService implements IUserManagerService {

	@Override
	public NmAdmin findUserByName(String username) {
		NmAdmin admin = (NmAdmin) iBaseDao.getObjectByHql("from NmAdmin a where a.username = ? ", username);
		Set<NmRole> nmRoles = admin.getRoleSet();
		for (NmRole nmRole : nmRoles) {
			Hibernate.initialize(nmRole.getResourceSet());
		}
		return admin;
	}

	@Override
	public Page findUsersByPage(Map<String, Object> map, NmAdmin admin) {
		
		return null;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void save(NmAdmin user) {
		user.setPassword(new Md5Hash(user.getPassword(), user.getUsername()).toHex());
		this.iBaseDao.insertObject(user);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void delete(NmAdmin user) {
		String[] ids = user.getId().split("-");
		for(String id : ids) {
			this.iBaseDao.updateByHql("delete from t_admin t where t.id = ? ", id);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void update(NmAdmin user) {
		this.iBaseDao.updateObject(user);
	}

	@Override
	public NmAdmin getUserById(String id) {
		return (NmAdmin) this.iBaseDao.getObject(NmAdmin.class, id);
	}
	
}
